<template>
  <div class="movie-list">
    <!-- 原始数据表格 -->
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="card-title">原始数据</span>
          <div class="button-group">
            <el-button :icon="Refresh" @click="fetchData">
              刷新列表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 数据加载中状态 -->
      <div v-loading="loading" element-loading-text="数据加载中...">
        <!-- 数据展示表格 -->
        <el-table
          :data="movieData"
          style="width: 100%"
          border
          :max-height="400"
          :header-cell-style="{
            background: '#f5f7fa',
            color: '#606266',
            fontWeight: 500
          }"
          :cell-style="(_, __, row) => getCellStyle(row, false)"
        >
          <el-table-column
            prop="movie_name"
            label="电影名称"
            min-width="180"
            fixed="left"
            header-align="center"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="release_info"
            label="发行信息"
            min-width="120"
            header-align="center"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="split_box_rate"
            label="分账占比"
            min-width="100"
            header-align="center"
            align="center"
          >
            <template #default="{ row }">
              {{ row.split_box_rate || '<0.1%' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="show_count"
            label="场次"
            min-width="100"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="show_count_rate"
            label="场次占比"
            min-width="100"
            header-align="center"
            align="center"
          >
            <template #default="{ row }">
              {{ row.show_count_rate || '<0.1%' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="sum_box_desc"
            label="总票房"
            min-width="120"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="updated_at"
            label="更新时间"
            min-width="160"
            fixed="right"
            header-align="center"
            align="center"
          >
            <template #default="{ row }">
              {{ formatDateTime(row.updated_at) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 原始数据表格分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 清洗后数据表格 -->
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="card-title">清洗后数据</span>
          <div class="button-group">
            <el-button :icon="Refresh" @click="fetchCleanedData">
              刷新列表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 数据加载中状态 -->
      <div v-loading="cleanedLoading" element-loading-text="数据加载中...">
        <!-- 数据展示表格 -->
        <el-table
          :data="cleanedMovieData"
          style="width: 100%"
          border
          :max-height="400"
          :header-cell-style="{
            background: '#f5f7fa',
            color: '#606266',
            fontWeight: 500
          }"
          :cell-style="(_, __, row) => getCellStyle(row, true)"
        >
          <el-table-column
            prop="movie_name"
            label="电影名称"
            min-width="180"
            fixed="left"
            header-align="center"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="release_info"
            label="发行信息"
            min-width="120"
            header-align="center"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="split_box_rate"
            label="分账占比"
            min-width="100"
            header-align="center"
            align="center"
          >
            <template #default="{ row }">
              {{ row.split_box_rate || '<0.1%' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="show_count"
            label="场次"
            min-width="100"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="show_count_rate"
            label="场次占比"
            min-width="100"
            header-align="center"
            align="center"
          >
            <template #default="{ row }">
              {{ row.show_count_rate || '<0.1%' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="sum_box_desc"
            label="总票房"
            min-width="120"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="updated_at"
            label="更新时间"
            min-width="160"
            fixed="right"
            header-align="center"
            align="center"
          >
            <template #default="{ row }">
              {{ formatDateTime(row.updated_at) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 清洗后数据表格分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="cleanedTotal"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getMovies, getCleanedMovies } from '@/api/movie'

// 原始数据相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const movieData = ref([])

// 清洗后数据相关
const cleanedTotal = ref(0)
const cleanedLoading = ref(false)
const cleanedMovieData = ref([])

// 获取原始数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getMovies()
    if (res.status === 'success' && Array.isArray(res.data)) {
      movieData.value = res.data.slice(
        (currentPage.value - 1) * pageSize.value,
        currentPage.value * pageSize.value
      )
      total.value = res.data.length
    } else {
      movieData.value = []
      total.value = 0
      ElMessage.warning('暂无电影数据')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error?.response?.data?.message || '获取数据失败，请检查网络连接')
    movieData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取清洗后数据
const fetchCleanedData = async () => {
  cleanedLoading.value = true
  try {
    const res = await getCleanedMovies()
    if (res.status === 'success' && Array.isArray(res.data)) {
      cleanedMovieData.value = res.data.slice(
        (currentPage.value - 1) * pageSize.value,
        currentPage.value * pageSize.value
      )
      cleanedTotal.value = res.data.length
    } else {
      cleanedMovieData.value = []
      cleanedTotal.value = 0
      ElMessage.warning('暂无清洗后数据')
    }
  } catch (error) {
    console.error('获取清洗后数据失败:', error)
    ElMessage.error(error?.response?.data?.message || '获取清洗后数据失败，请检查网络连接')
    cleanedMovieData.value = []
    cleanedTotal.value = 0
  } finally {
    cleanedLoading.value = false
  }
}

// 统一的分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  // 同时刷新两个表格
  fetchData()
  fetchCleanedData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 同时刷新两个表格
  fetchData()
  fetchCleanedData()
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  const date = new Date(datetime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 比较两个数据是否相等
const isEqual = (val1, val2) => {
  if (val1 === val2) return true
  if (val1 === null || val2 === null) return false
  if (typeof val1 === 'object' && typeof val2 === 'object') {
    return JSON.stringify(val1) === JSON.stringify(val2)
  }
  return String(val1) === String(val2)
}

// 获取单元格样式
const getCellStyle = (row, isCleaned) => {
  if (!row) return {}
  
  const compareData = isCleaned ? movieData.value : cleanedMovieData.value
  if (!compareData || !Array.isArray(compareData)) return {}
  
  const compareRow = compareData.find(item => item && item.movie_name === row.movie_name)
  
  if (!compareRow) {
    return {
      backgroundColor: '#fef0f0',  // 红色背景，表示数据在另一个表格中不存在
      color: '#f56c6c'
    }
  }

  const isDifferent = !isEqual(row.release_info, compareRow.release_info) ||
    !isEqual(row.split_box_rate, compareRow.split_box_rate) ||
    !isEqual(row.show_count, compareRow.show_count) ||
    !isEqual(row.show_count_rate, compareRow.show_count_rate) ||
    !isEqual(row.sum_box_desc, compareRow.sum_box_desc)

  if (isDifferent) {
    return {
      backgroundColor: '#fdf6ec',  // 黄色背景，表示数据有差异
      color: '#e6a23c'
    }
  }

  return {}
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
  fetchCleanedData()
})
</script>

<style scoped>
.movie-list {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
}

.button-group {
  display: flex;
  gap: 8px;
}

.mb-4 {
  margin-bottom: 24px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

:deep(.el-table) {
  margin-bottom: 20px;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: var(--el-fill-color-light) !important;
  font-weight: 500 !important;
  color: var(--el-text-color-primary) !important;
  padding: 12px 0 !important;
}

:deep(.el-table td) {
  padding: 12px 0 !important;
}

:deep(.el-table .cell) {
  padding: 0 8px !important;
  white-space: nowrap;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid var(--el-table-border-color) !important;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.el-table td.different) {
  background-color: #fdf6ec !important;
  color: #e6a23c !important;
}

:deep(.el-table td.missing) {
  background-color: #fef0f0 !important;
  color: #f56c6c !important;
}
</style> 